<?php

namespace App\Http\Middleware;

use App\Http\Services\ApiService;
use App\Http\Services\MsgService;
use Closure;
use App\Http\Helpers\Sign;

class SignRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        $data = $request->except('s');
        $data = json_decode(file_get_contents("php://input"), true);
        Sign::writeLog("sign_request_middleware：", $data, 'open');
        $type = isset($data['type']) ? $data['type'] : 'open';
        if(in_array($type, ['trigger', 'manage', 'monitor'])){
            return $next($request);
        }
        // 参数验证
        $validate = app('validator')->make($data, [
            'school_code' => 'required',
//            'type' => 'required',
            'app_key' => 'required',
            'timestamp' => 'required|int',
            'signature' => 'required',
            'nonce' => 'required',
        ]);
        if($validate->fails()){
            Sign::writeLog("参数不正确：", __LINE__, 'open');
            return response()->json(MsgService::getInterfaceMsg(1004));
        }
        $signature = $data['signature'];
        $needSign = array_except($data, ['url', 'type', 'signature']);
        $sign = Sign::colsign($needSign, ApiService::APP_SECRET);
        if($signature != $sign){
            Sign::writeLog("签名错误：", __LINE__, 'open');
            return response()->json(MsgService::getInterfaceMsg(1005));
        }

        //时间戳验证
        $interval = time() - $data['timestamp'];
        if($interval < 0 || $interval > 100000000){
            Sign::writeLog("请求超时：", __LINE__, 'open');
            return response()->json(MsgService::getInterfaceMsg(1006));
        }
        Sign::writeLog("通过中间件：", __LINE__, 'open');
        $request->replace($data);
        return $next($request);
    }
}
